package cn.chimade.mom.mis.servlet;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

/**
 * Proxy all spc-portlet UI request
 * @author Miller Huang
 *
 */
public class JsonActionProxy extends HttpServlet {
	
	protected static Logger logger = Logger.getLogger( JsonActionProxy.class );

    public JsonActionProxy() {
    	
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        dealSend(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException  {
        dealSend(request, response);
    }
    protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException  {
    	dealSend(request, response);
    }
    
    protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException  {
    	dealSend(request, response);
    }
    protected void doTrace(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException  {
    	dealSend(request, response);
    }
    
    protected void doHead(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException  {
    	dealSend(request, response);
    }
    
    protected void doOptions(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException  {
    	dealSend(request, response);
    }

    private void dealSend(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int timeout;
        response.setHeader("Content-type", "text/html;charset=UTF-8"); 
        StringBuffer urlBuf;
        HttpURLConnection httpURLConnection = null;
        OutputStream outputStream = null;
    	BufferedReader br  = null;
        timeout = 600000;
        if(request.getParameter("hostUrl") == null)
        	return ;
        urlBuf = new StringBuffer();
        urlBuf.append(request.getParameter("hostUrl")).append("?") ;
        Enumeration<String> paraNames = request.getParameterNames();
 
        String serverKey = "http://127.0.0.1:8090/";
        
        if(paraNames != null)
            while(paraNames.hasMoreElements()) {
                String name = (String)paraNames.nextElement();
                
                if (name.equals("serverKey")) {
                    serverKey = request.getParameter(name);
                    continue;
                }
                
                if(!name.equals("hostUrl") && !name.equals("_dc")) {
                	String value = request.getParameter(name) ; 
                	value = value.replaceAll(" ", "%20");
                    urlBuf.append("&").append(name).append("=").append( value );
                }
            }
        
        String url = (new StringBuilder(serverKey)).append(urlBuf.toString()).toString();
        try {
            URL u = new URL(url);
            httpURLConnection = (HttpURLConnection)u.openConnection();
        	httpURLConnection.setRequestMethod(   request.getMethod() );
          /*  if(request.getMethod().equalsIgnoreCase("GET"))
                httpURLConnection.setRequestMethod("GET");
            else  if(request.getMethod().equalsIgnoreCase("POST"))
                httpURLConnection.setRequestMethod("POST");
            else  if(request.getMethod().equalsIgnoreCase("DELETE"))
            	httpURLConnection.setRequestMethod("DELETE");
            else  if(request.getMethod().equalsIgnoreCase("PUT"))
            	httpURLConnection.setRequestMethod("PUT");
            else  if(request.getMethod().equalsIgnoreCase("HEAD"))
            	httpURLConnection.setRequestMethod("HEAD");
            else if (request.getMethod().equalsIgnoreCase("TRACE"))
            	httpURLConnection.setRequestMethod("TRACE");
            else  if(request.getMethod().equalsIgnoreCase("OPTIONS"))
            	httpURLConnection.setRequestMethod("OPTIONS");
            */
            String payloadRequest = getBody(request);
            httpURLConnection.setUseCaches(false);
            httpURLConnection.setAllowUserInteraction(false);
            httpURLConnection.setConnectTimeout(timeout);
            httpURLConnection.setReadTimeout(timeout);
            if(payloadRequest != null && !payloadRequest.trim().equals("")) {
            	 if(	!request.getMethod().equalsIgnoreCase("DELETE") ) {
            		 httpURLConnection.setDoOutput(true);
	                httpURLConnection.setDoInput(true);
	                httpURLConnection.setRequestProperty("Content-type", "application/json;charset=UTF-8");
	                httpURLConnection.setRequestProperty("X-Requested-With", "XMLHttpRequest");
	                httpURLConnection.setFixedLengthStreamingMode(payloadRequest.getBytes().length);
	                outputStream = new BufferedOutputStream(httpURLConnection.getOutputStream());
	                outputStream.write(payloadRequest.getBytes());
	                outputStream.flush();
	           	 } else{
	           		httpURLConnection.setRequestProperty("Content-Type",  "application/x-www-form-urlencoded");
	           	 }
            } else {
                httpURLConnection.setRequestProperty("Content-length", "0");
            }
            
            httpURLConnection.connect();
            int status = httpURLConnection.getResponseCode();
            switch(status) {
            	case 200: 
            	case 201: 
            		  br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
            		StringBuilder sb = new StringBuilder();
            		String line;
            		while((line = br.readLine()) != null) 
            			sb.append((new StringBuilder(String.valueOf(line))).append("\n").toString());
//            		br.close();
            		response.getWriter().write(sb.toString());
            		break;
            }
           
        } catch(Exception ex) {
        	ex.printStackTrace();
        	String msg = ex.toString() ;
        	msg = msg.replace('\n', '_').replace('\r','_');
        	logger.error(  msg + " "+url);
        } finally {
        	if ( br != null)
        		br.close();
	        if(outputStream != null)
	            outputStream.close();
	        if(httpURLConnection != null)
	            httpURLConnection.disconnect();
        }
    }

    public static String getBody(HttpServletRequest request) throws IOException {
    	String body = null;
        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader bufferedReader = null;
        InputStream inputStream =null ; 
        try {
        	inputStream  = request.getInputStream();
            if (inputStream != null) {
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                char[] charBuffer = new char[128];
                int bytesRead = -1;
                while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
                    stringBuilder.append(charBuffer, 0, bytesRead);
                }
            } else {
                stringBuilder.append("");
            }
        } catch (IOException ex) {
            logger.error(ex);
        } finally {
        	if ( inputStream != null )
        		inputStream.close();
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException ex) {
                    throw ex;
                }
            }
        }
        body = stringBuilder.toString();
        return body;
    }
 
    private static final long serialVersionUID = 0x6b1798d0880e0807L;
}
